package userHelp

import (
	myConfig "common/config"
	myredis "common/redis"
	"context"
	"fmt"
	"github.com/jmoiron/sqlx"
	"github.com/valyala/fasthttp"
	"time"
)

func RegisetTable(tableName string, tableField *StTableField) {
	g_mapTableField[tableName] = *tableField
}

func LoadUserToRedis(uid string) {

	if myredis.IsUserExis(string(uid)) {
		return
	}

	for tableName, fieldInfo := range g_mapTableField {
		sqlStr := getSelectSql(tableName, &fieldInfo, AccountId(uid))
		//println(sqlStr)

		setToRedis(tableName, &fieldInfo, sqlStr, AccountId(uid))
	}

	LoadUserWage(uid)
	redisKey := fmt.Sprintf("UserId:%s", uid)
	myredis.GetRedisInstance().HSet(context.Background(), redisKey, "lastUpdateTime", time.Now().Unix())
	return
}

func LoadModuleInit(sql *sqlx.DB, funcSetRedis FuncSetRedis) {
	g_mapTableField = make(map[string]StTableField)
	g_sql = sql
	g_funcSetFieldRedis = funcSetRedis

	RegisetTable("tbl_member_base", &StTableField{fieldStruct: TblMemberBase{}})
	RegisetTable("tbl_member_adjust", &StTableField{fieldStruct: TblMemberAdjust{}})
	RegisetTable("tbl_member_balance", &StTableField{fieldStruct: TblMemberBalance{}})
	RegisetTable("tbl_member_accu", &StTableField{fieldStruct: TblMemberAccu{}})
	RegisetTable("tbl_member_lottery", &StTableField{fieldStruct: TblMemberLottery{}})
	RegisetTable("tbl_pdd_turntable_info", &StTableField{fieldStruct: TblPddTurntableInfo{}})
	RegisetTable("tbl_member_status", &StTableField{fieldStruct: TblMemberStatus{}})
	RegisetTable("tbl_member_return", &StTableField{fieldStruct: TblMemberWeekReturn{}})
	RegisetTable("tbl_proxy_base", &StTableField{fieldStruct: TblProxyBase{}})
	RegisetTable("tbl_member_controller_button", &StTableField{fieldStruct: MemberControllerButton{}})
	RegisetTable("tbl_member_vip", &StTableField{fieldStruct: TblMemberVIP{}})
	RegisetTable("tbl_member_piggy_bank", &StTableField{fieldStruct: TblPiggyBank{}})
	RegisetTable("tbl_member_disbind_area", &StTableField{fieldStruct: TblMemberDisbindArea{}})
	RegisetTable("tbl_member_info", &StTableField{fieldStruct: TblMemberInfo{}})
}

/*
var AllMemTableName [10]string = [10]string{
	"tbl_member_adjust", "tbl_member_balance", "tbl_member_bankcard", "tbl_member_base", "tbl_member_deposit_info",
	"tbl_member_level_downgrade", "tbl_member_level_record", "tbl_member_platform", "tbl_member_proxy_accu", "tbl_member_return",
}
*/

func SwitchTableStruct(tableName string) interface{} {
	var data interface{}
	switch tableName {
	case "tbl_admin_group":
		data = &TblAdminGroup{}
	case "tbl_admin_group_tree":
		data = &TblAdminGroupTree{}
	case "tbl_admin_priv":
		data = &TblAdminPriv{}
	case "tbl_admins":
		data = &TblAdmins{}
	case "tbl_app_upgrade":
		data = &TblAppUpgrade{}
	case "tbl_balance_transaction":
		data = &TblBalanceTransaction{}
	case "tbl_banktype":
		data = &TblBankType{}
	case "tbl_banner":
		data = &TblBanner{}
	case "tbl_bonus_config":
		data = &TblBonusConfig{}
	case "tbl_business_info":
		data = &TblBusinessInfo{}
	case "tbl_deposit":
		data = &tblDeposit{}
	case "tbl_flow_config":
		data = &TblFlowConfig{}
	//case "tbl_game_config":data = &(myConfig.TblGameConfig{})
	case "tbl_game_lists":
		data = &TblGameLists{}
	case "tbl_game_record":
		data = &TblGameRecord{}
	case "tbl_game_tag_idx":
		data = &TblGameTagIdx{}
	case "tbl_game_tag_name":
		data = &TblGameTagName{}
	case "tbl_member_adjust":
		data = &TblMemberAdjust{}
	case "tbl_member_balance":
		data = &TblMemberBalance{}
	case "tbl_member_bankcard":
		data = &TblMemberBankcard{}
	case "tbl_member_base":
		data = &TblMemberBase{}
	case "tbl_member_deposit_info":
		data = &TblMemberDepositInfo{}
	case "tbl_member_level_downgrade":
		data = &TblMemberLevelDowngrade{}
	case "tbl_member_level_record":
		data = &TblMemberLevelRecord{}
	case "tbl_member_platform":
		data = &TblMemberPlatform{}
	case "tbl_member_test":
		data = &TblMemberTest{}
	case "tbl_members_tree":
		data = &TblMembersTree{}
	case "tbl_messages":
		data = &TblMessage{}
	case "tbl_notices":
		data = &TblNotices{}
	case "tbl_operator_domain":
		data = &TblOperatorDomain{}
	case "tbl_operator_info":
		data = &TblOperatorInfo{}
	case "tbl_pay_factory":
		data = &TblPayFactory{}
	case "tbl_pdd_turntable_history":
		data = &TblPddTurntableHistory{}
	case "tbl_pdd_turntable_info":
		data = &TblPddTurntableInfo{}
	case "tbl_pdd_turntable_review":
		data = &TblPddTurntableReview{}
	case "tbl_platforms":
		data = &TblPlatforms{}
	case "tbl_promo_deposit":
		data = &TblPromoDeposit{}
	case "tbl_promo_inspection":
		data = &TblPromoInspection{}
	case "tbl_promo_invite_record":
		data = &TblPromoInviteRecord{}
	case "tbl_promo_sign_config":
		data = &TblPromoSignConfig{}
	case "tbl_promo_sign_record":
		data = &TblPromoSignRecord{}
	case "tbl_promo_sign_reward_record":
		data = &TblPromoSignRewardRecord{}
	case "tbl_promo_treasure_config":
		data = &TblPromoTreasureConfig{}
	case "tbl_promo_treasure_record":
		data = &TblPromoTreasureRecord{}
	case "tbl_promo_weekbet_config":
		data = &TblPromoWeekBetConfig{}
	case "tbl_promo_weekbet_record":
		data = &TblPromoWeekbetRecord{}
	case "tbl_rebate_record":
		data = &TblRebateRecord{}
	case "tbl_report_agency":
		data = &TblReportAgency{}
	case "tbl_report_daily":
		data = &TblReportDaily{}
	case "tbl_report_game":
		data = &TblReportGame{}
	case "tbl_report_game_daily":
		data = &TblReportGameDaily{}
	case "tbl_report_platform":
		data = &TblReportPlatform{}
	case "tbl_report_proxy_daily":
		data = &TblReportProxyDaily{}
	case "tbl_report_proxy_daily_1":
		data = &TblReportProxyDaily1{}
	case "tbl_report_user":
		data = &TblReportUser{}
	case "tbl_report_user_daily":
		data = &TblReportUserDaily{}
	case "tbl_transaction_types":
		data = &TblTransactionTypes{}
	case "tbl_whitelist":
		data = &TblWhitelist{}
	case "tbl_withdraw":
		data = &TblWithdraw{}
	case "tbl_member_accu":
		data = &TblMemberAccu{}
	case "tbl_member_lottery":
		data = &TblMemberLottery{}
	case "tbl_member_status":
		data = &TblMemberStatus{}
	case "tbl_member_return":
		data = &TblMemberWeekReturn{}
	case "tbl_proxy_base":
		data = &TblProxyBase{}
	case "tbl_member_controller_button":
		data = &MemberControllerButton{}
	case "tbl_member_piggy_bank":
		data = &TblPiggyBank{}
	case "tbl_member_vip":
		data = &TblMemberVIP{}
	case "tbl_member_disbind_area":
		data = &TblMemberDisbindArea{}
	case "tbl_member_info":
		data = &TblMemberInfo{}
	}

	return data
}

func GetPddTurntableInfo(uid string) (TblPddTurntableInfo, bool) {
	tblPddInfo := TblPddTurntableInfo{}

	LoadUserToRedis(uid)
	if !myredis.IsUserExis(uid) {
		return tblPddInfo, false
	}

	tblPddInfo.Uid = uid
	uidKey := myredis.GetUserRedisKey(uid)

	intMap := myredis.HMGetFieldInt(uidKey, []string{"unuse_chance", "used_chance", "enabled"})
	tblPddInfo.UnuseChance = intMap["unuse_chance"]
	tblPddInfo.UsedChance = intMap["used_chance"]
	tblPddInfo.Enabled = intMap["enabled"]

	float64Map := myredis.HMGetFieldFloat64(uidKey, []string{"amount", "hand_amount", "tot_amount"})
	tblPddInfo.Amount = float64Map["amount"]
	tblPddInfo.HandAmount = float64Map["hand_amount"]
	tblPddInfo.TotAmount = float64Map["tot_amount"]

	int64Map := myredis.HMGetFieldInt64(uidKey, []string{"created_at", "updated_at"})
	tblPddInfo.CreatedAt = int64Map["created_at"]
	tblPddInfo.UpdatedAt = int64Map["updated_at"]

	return tblPddInfo, true
}

func GetUidFromToken(fctx *fasthttp.RequestCtx) string {
	value := fctx.UserValue("token")
	if value == nil {
		return ""
	}

	uid := string(value.([]byte))
	return uid
}

/*
获取代理的邀请奖励
*/
func GetProxyInviteBonus(parentId string, childDepositAmount float64) float64 {
	if myConfig.IsActiveOpen(myConfig.ActiveType_ProxyBonus_ByValidCounts) > 0 {
		return myConfig.GetGameCfgFloat64(myConfig.CfgInvitedBonus)
	}
	return 0
}

/*
计算玩家的税收
*/

func GetGameTax(Uid, platformId string, gameWin, gameBet float64) float64 {

	realGameWin := gameWin - gameBet
	balance := GetBalanceFloat64ByUid(Uid)

	if G_UserButton.GetTax(Uid) == ButtonClose ||
		myConfig.GetGameCfgInt(myConfig.CfgGlobalTaxSwitch) == 0 || !myConfig.IsThirdOpenTax(platformId) {
		return 0.00
	}

	//盈利金额是否小数,开启--只抽盈利金额为小数的税,关闭--都抽
	if balance > myConfig.GetGameCfgFloat64(myConfig.CfgTaxConditionBalance) &&
		realGameWin > myConfig.GetGameCfgFloat64(myConfig.CfgTaxConditionGameWin) {
		if myConfig.GetGameCfgInt(myConfig.CfgIsTheProfitAmountDecimal) == 0 {
			taxRate := myConfig.GetTaxRate(realGameWin)
			return float64(taxRate) / 100 * realGameWin
		} else {
			if isDecimal(realGameWin) {
				taxRate := myConfig.GetTaxRate(realGameWin)
				return float64(taxRate) / 100 * realGameWin
			} else {
				return 0.00
			}
		}
	}

	return 0.00
}

/*
获取玩家的可提余额
*/
func GetEnableWithdrawMount(uid string) float64 {

	Balance := GetBalanceFloat64ByUid(uid)
	var EnableWithdrawMount float64
	ID := myredis.GetUserFieldInt64(uid, g_tbl_member_wage_require+"ID")
	if ID == 0 {
		//无打码任务 返回当前余额
		EnableWithdrawMount = Balance
	} else {
		WagedModeCfg := myConfig.GetGameCfgInt(myConfig.CfgWagedMode)

		if WagedModeCfg == 0 {
			unlockAmount := GetUnlockAmount(uid)
			AgencyAmount := GetAgencyAmount(uid)

			if unlockAmount > AgencyAmount {
				EnableWithdrawMount = unlockAmount
			} else {
				EnableWithdrawMount = AgencyAmount
			}
		} else {
			//打码未完成的条数
			SQLSelect := fmt.Sprintf("select count(1) from tbl_member_wage_require where uid=%s and Status=0", uid)

			var WageItemUnfinish int = 1
			g_sql.Get(&WageItemUnfinish, SQLSelect)

			if WageItemUnfinish > 0 {
				EnableWithdrawMount = 0
			} else {
				EnableWithdrawMount = Balance
			}
		}
	}

	if EnableWithdrawMount > Balance {
		EnableWithdrawMount = Balance
	}

	return EnableWithdrawMount
}

// 判断是不是小数
func isDecimal(num float64) bool {
	return num-float64(int(num)) != 0
}
